package com.example.zhu.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhu.config.BaseContext;
import com.example.zhu.dto.*;
import com.example.zhu.entity.AddressBook;
import com.example.zhu.entity.Transactions;
import com.example.zhu.entity.UserMoney;
import com.example.zhu.entity.Users;
import com.example.zhu.mapper.*;
import com.example.zhu.result.Result;
import com.example.zhu.service.AddressBookService;

import com.example.zhu.vo.OrderVOMax;
import com.example.zhu.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.example.zhu.service.Impl.OrderServiceImpl.getNum;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private MoneyMapper moneyMapper;
    @Autowired
    private TransactionMapper transactionMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private WithdrawMapper withdrawMapper;

    /**
     * 查询所有用户信息
     * @return
     */
    public List<UserVo> selectAllAddress() {

        //获取地址簿列表
        List<AddressBook> addressBookList = addressBookMapper.selectAll();
        //创建返回结果集合
        List<UserVo> userVos = new ArrayList<>();
        //对地址簿遍历
        for (AddressBook addressBook : addressBookList) {
            if(addressBook.getIsDefault()==1){
                //查询地址信息,用户信息
                String openid = addressBook.getOpenid();
                Users user = usersMapper.selectByOpenid(openid);

                //查询money信息
                UserMoney userMoney = usersMapper.selectMoney(openid);
                UserVo userVo = new UserVo();
                if (userMoney!=null){
                    userVo.setMoney(userMoney.getMoney());
                    userVo.setPaopaoCoins(userMoney.getPaopaoCoins());
                }else {
                    userVo.setMoney(0);
                    userVo.setPaopaoCoins(0);
                }
                userVo.setPhone(addressBook.getPhone());
                if(user.getType()==-1){
                    userVo.setState(0);
                }else {
                    userVo.setState(1);
                }
                userVo.setType(user.getType());
                userVo.setId(Math.toIntExact(addressBook.getId()));
                userVo.setAddress(addressBook.getAddress());
                userVos.add(userVo);
            }

        }
        return userVos;
    }

    /**
     * TODO 删除地址
     * @param id
     */
    public void deleteAddress(Integer id) {

        UserVo userVo = addressBookMapper.getDA(id);
        String openid = userVo.getOpenid();

        //address_book表
        addressBookMapper.deleteAddress(id);
        //users表
        usersMapper.deleteByUserId(id);
        //coupon_book表
        couponMapper.deleteByOpenid(openid);
        //orders表
        orderMapper.deleteByOpenid(openid);
        //take_orders表
        orderMapper.deleteTakeOrder(openid);
        //user_money表
        moneyMapper.deleteByOpenid(openid);
        //withdraw表
        withdrawMapper.deleteByOpenid(openid);
    }

    /**
     * 根据手机号查询
     * @param phone
     * @return
     */
    public List<UserVo> getByPhone(String phone) {
        List<UserVo> userVo = addressBookMapper.getByPhone(phone);
        for (UserVo vo : userVo) {
            UserMoney userMoney = usersMapper.selectMoney(vo.getOpenid());
            if(userMoney!=null){
                vo.setMoney(userMoney.getMoney());
                vo.setPaopaoCoins(userMoney.getPaopaoCoins());
            }else {
                vo.setPaopaoCoins(0);
                vo.setMoney(0);
            }
            if(vo.getType()==-1){
                vo.setState(0);
            }else {
                vo.setState(1);
            }
        }
        return userVo;
    }

    /**
     * 根据多区域查询用户信息 排序
     * @param areas
     * @return
     */
    public List<UserVo> getByAreas(List<String> areas) {

        List<UserVo> list = selectAllAddress();
        List<UserVo> res = new ArrayList<>();
        for (int i = 0; i < areas.size() - 1; i++) {
            for (int j = 0; j < areas.size() - i - 1; j++) {
                String s = areas.get(j);
                String w = areas.get(j + 1);
                String num1 = getNum(s);
                String num2 = getNum(w);
                Integer x = Integer.parseInt(num1);
                Integer y = Integer.parseInt(num2);
                if (x > y) {
                    String s1 = areas.get(j);
                    String s2 = areas.get(j + 1);
                    areas.set(j,s2);
                    areas.set(j+1,s1);
                }
            }
        }
        for (String area : areas) {
            Integer index = res.size();
            for (int i = 0; i < list.size(); i++) {
                UserVo userVo = list.get(i);
                String s = userVo.getAddress();
                String[] split = s.split("/");
                if(area.equals(split[0])){
                    res.add(userVo);
                }
            }

            //  TODO 二层地址 如何排序
            for (int i = index; i < res.size() - 1; i++) {
                for (int j = index; j < res.size() + index - i - 1; j++) {
                    UserVo userVo = res.get(j);
                    UserVo userVo_ = res.get(j + 1);
                    String address = userVo.getAddress();
                    String address_ = userVo_.getAddress();
                    String[] split = address.split("/");
                    String[] split_ = address_.split("/");
                    String num;
                    String num_;
                    int number = Integer.MAX_VALUE;
                    int number_ = Integer.MAX_VALUE;
                    if (split_.length >= 3) {
                        num_ = split_[2];
                        number_ = Integer.parseInt(num_);
                    }
                    if(split.length>=3){
                        num = split[2];
                        number = Integer.parseInt(num);

                    }

//                    int floor1 = number / 100;
//                    int floor2 = number_ / 100;
                        if (number > number_) {
                            UserVo t = res.get(j);
                            UserVo t_ = res.get(j + 1);
                            res.set(j, t_);
                            res.set(j + 1, t);
                        }


                }
            }

        }
        return res;

    }


    /**
     * 修改用户信息
     * @param editAddressDTO
     * @return
     */
    @Transactional
    public Result<String> editInfo(EditAddressDTO editAddressDTO) {

        //如果状态为0， 修改type字段为-1，表示禁用该账号
        if (editAddressDTO.getState()==0){
            editAddressDTO.setType(-1);
        }

        //更新除了钱之外的记录信息
        //更新user表信息
//        TODO 更新addressbook表的信息

        //获得地址id
        Integer id = editAddressDTO.getId();
        AddressBook addressBook = addressBookMapper.selectById(id);
        String openid = addressBook.getOpenid();

        usersMapper.updateByOpenid(openid,editAddressDTO.getType());

        //准备生成日志
        //获取修改后的跑跑币和余额
        Integer paopaoCoins = editAddressDTO.getPaopaoCoins();
        Integer money = editAddressDTO.getMoney();

        //获取修改前的跑跑币和金额
        UserMoney userMoney = usersMapper.selectMoney(openid);
        if(userMoney!=null){
            Integer coin = userMoney.getPaopaoCoins();
            Integer amount = userMoney.getMoney();
            log(openid,amount,money,coin,paopaoCoins);
            usersMapper.update(paopaoCoins,money,openid);
        }else {
            return Result.error("没有该用户的余额记录，无法操作");
        }

        return Result.success("修改成功");
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void log(String openid, Integer before, Integer after,Integer paopaoBefore,Integer paopaoAfter) {
        Transactions transactions = Transactions.builder().openid(BaseContext.getCurrentUsername())
                .takeOpenid(openid)
                .number(System.currentTimeMillis())
                .coinsBefore(paopaoBefore)
                .coinsAfter(paopaoAfter)
                .moneyBefore(before)
                .moneyAfter(after)
                .transactionDate(LocalDateTime.now())
                .transactionType("管理员更改")
                .fee(0)
                .build();
        transactionMapper.insert(transactions);
    }

    /**
     * 根据id查询用户默认地址
     * @param id
     * @return
     */
    public UserVo getDA(Integer id) {
        UserVo userVo = addressBookMapper.getDA(id);
        UserMoney userMoney = usersMapper.selectMoney(userVo.getOpenid());
        if(userMoney!=null) {
            userVo.setMoney(userMoney.getMoney());
            userVo.setPaopaoCoins(userMoney.getPaopaoCoins());
        }else{
            userVo.setMoney(0);
            userVo.setPaopaoCoins(0);
        }
        if(userVo.getType()==-1){
            userVo.setState(0);
        }else {
            userVo.setState(1);
        }
        return userVo;
    }
}
